/**Created by the LayaAirIDE*/
package view
{
	import ui.JoyStickUI
	import laya.maths.Point;
	import laya.events.Event;
	import laya.d3.core.Camera;
	import laya.d3.math.Vector3;
	import laya.d3.math.Quaternion;

	public class JoyStick extends JoyStickUI
	{
		protected var camera:Camera;
		protected var yawPitchRoll:Vector3 = new Vector3();
		protected var tempRotation:Quaternion = new Quaternion();

		private var startX:Number;
		private var startY:Number;
		private var MAX_DIS:int = 70;
		public function JoyStick() 
		{
			this.on(Event.MOUSE_DOWN,this,onMouseDown);
			this.on(Event.MOUSE_UP,this,onMouseUp);
			this.on(Event.MOUSE_OUT,this,onMouseOut);
		}

		public function bindCamera(camera:GameCamera):void
		{
			this.camera = camera;
		}
		
		private function onMouseDown():void
		{
			this.on(Event.MOUSE_MOVE,this,onMouseMove);
			startX = this.mouseX;
			startY = this.mouseY;

			setJoyPoint(startX,startY);
			Laya.timer.frameLoop(1,this,updateCamera);
		}

		private function onMouseUp():void
		{
			this.off(Event.MOUSE_MOVE,this,onMouseMove);
			setJoyPoint(img_joybg.x,img_joybg.y);
			Laya.timer.clear(this,updateCamera);
		}

		private function onMouseOut():void
		{
			this.off(Event.MOUSE_MOVE,this,onMouseMove);
			setJoyPoint(img_joybg.x,img_joybg.y);
			Laya.timer.clear(this,updateCamera);
		}

		private function onMouseMove():void
		{
			setJoyPoint(this.mouseX,this.mouseY);
		}
		
		private function setJoyPoint(x:Number,y:Number):void
		{
			var originX:int = img_joybg.x;
			var originY:int = img_joybg.x;
			var dx:int = x - originX;
			var dy:int = y - originY;
			//强制控制点与中心距离不超过60像素
			if(dx * dx + dy * dy > MAX_DIS * MAX_DIS)
			{
				var lenPer:Number = MAX_DIS / Math.sqrt(dx * dx + dy * dy);
				x = Math.floor(lenPer * dx) + originX;
				y = Math.floor(lenPer * dy) + originY;
			}
			img_joypoint.x = x;
			img_joypoint.y = y;
		}

		private function updateCamera():void
		{
			if(!camera)
				return;
			var dx:int = img_joypoint.x - img_joybg.x;
			var dy:int = img_joypoint.y - img_joybg.y;
			if(dx == 0 && dy == 0)
				return;
			var elapsedTime:int = Laya.timer.delta;
			var yprElem:Float32Array = yawPitchRoll.elements;
			yprElem[0] -= dx * GameManager.CAMERA_ROTATION_SPEED * elapsedTime;
			yprElem[1] -= dy * GameManager.CAMERA_ROTATION_SPEED * elapsedTime;
			Quaternion.createFromYawPitchRoll(yprElem[0], yprElem[1], yprElem[2], tempRotation);
			camera.transform.localRotation = tempRotation;
		}
	}

}